<template>
    <div class="app-container">
        <!-- 搜索 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
            <el-form-item label="省" prop="provinceId">
                <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
                    <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="市" prop="cityId">
                <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
                    <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="区/县" prop="prefectureId">
                <el-select v-model="queryParams.prefectureId" placeholder="请选择区/县" clearable>
                    <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button plain @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 按钮 -->
        <el-row :gutter="10" class="mb8" style="float:left">
            <el-col :span="1.5">
                <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
        </el-row>

        <div style="text-align: right;float: right;">
            <span>排列方式：</span>
            <el-radio-group v-model="queryParams.option" @change="handleQuery">
                <el-radio label="0">行政区划</el-radio>
                <el-radio label="1">更新时间倒序</el-radio>
            </el-radio-group>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </div>

        <!-- 列表 -->
        <el-table v-loading="loading" :data="dataList" stripe>
            <el-table-column label="省" align="center" prop="province" />
            <el-table-column label="市" align="center" prop="city" />
            <el-table-column label="区（县）" align="center" prop="prefecture" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button type="text" @click="handleView(scope.row)">查看</el-button>
                    <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <!-- 添加或修改区县概况信息 -->
        <el-dialog :title="title" v-if="showPopup" v-model="showPopup" width="1000px" append-to-body>
            <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px">
                <el-row class="mt15">
                    <el-col :span="8">
                        <el-form-item label="省" prop="provinceId">
                            <el-select v-model="form.provinceId" placeholder="请输入省" @change="chooseFormProvince"
                                :disabled="btnType !== 'add'" style="width: 100%;">
                                <el-option v-for="item in provinceFormData" :key="item.id" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市" prop="cityId">
                            <el-select v-model="form.cityId" placeholder="请输入市" @change="chooseFormCity"
                                :disabled="btnType !== 'add'" style="width: 100%;">
                                <el-option v-for="item in cityFormData" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区/县" prop="prefectureId">
                            <el-select v-model="form.prefectureId" placeholder="请输入区/县" @change="chooseFormArea"
                                :disabled="btnType !== 'add'" style="width: 100%;">
                                <el-option v-for="item in areaFormData" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <TabTable ref="tabTableRef" :form="form" :id="scId" :parentBtnType="btnType" />
                <el-form-item class="mt15" label="医疗救护情况" prop="scMedicalhelp">
                    <el-input v-model="form.scMedicalhelp" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入医疗救护情况" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="medicalFile" :disabled="btnType == 'check'" v-model="form.scMedicalhelpAttachment" />
                </el-form-item>
                <el-form-item label="报灾系统建设情况" prop="scBzxtjsqk">
                    <el-input v-model="form.scBzxtjsqk" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入报灾系统建设情况" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="bzxtjsFile" :disabled="btnType == 'check'" v-model="form.scBzxtjsqkAttachment" />
                </el-form-item>
                <el-form-item label="地震应急组织体系和预案体系" prop="scDzyjzztxhyatx">
                    <el-input v-model="form.scDzyjzztxhyatx" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入地震应急组织体系和预案体系" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="dzyjzztxFile" :disabled="btnType == 'check'"
                        v-model="form.scDzyjzztxhyatxAttachment" />
                </el-form-item>
                <el-form-item label="地震应急工作机制" prop="scDzyjgzjz">
                    <el-input v-model="form.scDzyjgzjz" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入地震应急工作机制" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="dzyjgzjzFile" :disabled="btnType == 'check'" v-model="form.scDzyjgzjzAttachment" />
                </el-form-item>
                <el-form-item label="应急演练开展情况" prop="scYjylkzqk">
                    <el-input v-model="form.scYjylkzqk" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入应急演练开展情况" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="yjylkzFile" :disabled="btnType == 'check'" v-model="form.scYjylkzqkAttachment" />
                </el-form-item>
                <el-form-item label="生命线应急保障情况" prop="scSmxyjbzqk">
                    <el-input v-model="form.scSmxyjbzqk" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入生命线应急保障情况" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="smxyjbzFile" :disabled="btnType == 'check'" v-model="form.scSmxyjbzqkAttachment" />
                </el-form-item>
                <el-form-item label="次生灾害防范情况" prop="scCszhffqk">
                    <el-input v-model="form.scCszhffqk" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入次生灾害防范情况" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="cszhffFile" :disabled="btnType == 'check'" v-model="form.scCszhffqkAttachment" />
                </el-form-item>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="是否有应急预案" prop="scSfyyjya">
                            <el-radio-group v-model="form.scSfyyjya">
                                <el-radio label="1">是</el-radio>
                                <el-radio label="0">否</el-radio>
                            </el-radio-group>

                        </el-form-item>
                        <el-form-item label="上传附件">
                            <file-upload ref="emergencyFile" :disabled="btnType == 'check'"
                                v-model="form.scSfyyjyaAttachment" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否有预案文件" prop="scSfyyawj">
                            <el-radio-group v-model="form.scSfyyawj">
                                <el-radio label="1">是</el-radio>
                                <el-radio label="0">否</el-radio>
                            </el-radio-group>

                        </el-form-item>
                        <el-form-item label="上传附件">
                            <file-upload ref="documentFile" :disabled="btnType == 'check'"
                                v-model="form.scSfyyawjAttachment" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="应急对策需求" prop="scYjdcxq">
                    <el-input v-model="form.scYjdcxq" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入应急对策需求" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="yjdcxqFile" :disabled="btnType == 'check'" v-model="form.scYjdcxqAttachment" />
                </el-form-item>
                <el-form-item label="重点目标保障能力" prop="scZdmbbznl">
                    <el-input v-model="form.scZdmbbznl" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入重点目标保障能力" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="zdmbbzFile" :disabled="btnType == 'check'" v-model="form.scZdmbbznlAttachment" />
                </el-form-item>
                <el-form-item label="谣言、舆情应急能力" prop="scYyyqyjnl">
                    <el-input v-model="form.scYyyqyjnl" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入谣言、舆情应急能力" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="yyyqyjnlFile" :disabled="btnType == 'check'" v-model="form.scYyyqyjnlAttachment" />
                </el-form-item>
                <el-form-item label="科普宣教和演练" prop="scKpxjhyl">
                    <el-input v-model="form.scKpxjhyl" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入科普宣教和演练" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="kpxjhylFile" :disabled="btnType == 'check'" v-model="form.scKpxjhylAttachment" />
                </el-form-item>
                <el-form-item label="其他地方特征应急准备措施" prop="scQtdftzyjzbcs">
                    <el-input v-model="form.scQtdftzyjzbcs" :disabled="btnType == 'check'" type="textarea" maxlength="2000"
                        show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入其他地方特征应急准备措施" />
                </el-form-item>
                <el-form-item label="上传附件">
                    <file-upload ref="qtdftzFile" :disabled="btnType == 'check'" v-model="form.scQtdftzyjzbcsAttachment" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm" v-show="btnType !== 'check'">确 定</el-button>
                    <el-button plain @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup name="emergencyPreparedness">
import { saveSeismicSetout, getAllSeismicSetout, getSeismicSetout, delSeismicSetout, updateSeismicSetout } from "@/api/basedatamanage/emergencyPreparedness.js";
import { getProvince, getChildArea } from "@/api/system/division";
import { getLanderRoles, getLanderProvince } from "@/api/basedatamanage/common.js"
import TabTable from "./tabTable.vue";
const { proxy } = getCurrentInstance();
const dataList = ref([]);  //列表
let loading = ref(false);   //加载状态
let btnType = ref(""); //按钮状态
let showPopup = ref(false);  // 弹框
let total = ref(0);   //列表总条数
let title = ref("");  //弹框title
let showSearch = ref(true);   //是否显示搜索项
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县
const provinceFormData = ref([]);//表单省 
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县
let scId = ref("")
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        provinceId: null,
        cityId: null,
        areaId: null,
        option: '0'
    },
    form: {},
    rules: {
        provinceId: [{ required: true, message: '请选择省', trigger: 'blur' }],
        cityId: [{ required: true, message: '请选择市', trigger: 'blur' }],
        prefectureId: [{ required: true, message: '请选择区/县', trigger: 'blur' }],
        scSfyyjya: [{ required: true, message: '请选择是否有应急预案', trigger: 'blur' }],
        scSfyyawj: [{ required: true, message: '请选择是否有预案文件', trigger: 'blur' }],
    }
})
const { queryParams, form, rules } = toRefs(data)

/** 查询区县概况列表 */
function getList() {
    loading.value = true;
    getAllSeismicSetout(queryParams.value).then(response => {
        dataList.value = response.data.rows;;
        total.value = response.data.total;
        loading.value = false;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    dataList.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
}
// 重置表单
function reset() {
    form.value = {
        province: '',
        city: '',
        prefecture: '',
        scSfyyjya: '0',
        scSfyyawj: '0',
    }
    proxy.resetForm("ruleFormRef");
}

/** 取消按钮 */
function cancel() {
    showPopup.value = false;
    reset();
};
/** 新增按钮操作 */
function handleAdd() {
    scId.value = ""
    reset();
    btnType.value = 'add';
    showPopup.value = true;
    title.value = "添加应急准备情况";
    getProvinceFormData();
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    btnType.value = 'edit';
    const id = row.scId || '';
    scId.value = id;
    getSeismicSetout(id).then(response => {
        editProvinceFormData(response.data.provinceId, response.data.cityId)
        form.value = { ...response.data };
        form.value.id = response.data.scId;
        showPopup.value = true;
        title.value = "修改应急准备情况";
    });
}

/** 查看按钮操作 */
function handleView(row) {
    reset();
    btnType.value = 'check';
    const id = row.scId || '';
    scId.value = id;
    getSeismicSetout(id).then(response => {
        editProvinceFormData(response.data.provinceId, response.data.cityId);
        form.value = { ...response.data };
        form.value.id = response.data.scId;
        showPopup.value = true;
        title.value = "查看区县概况信息";
    });
}


//修改后省市区赋值
function editProvinceFormData(provinceId, cityId) {
    getProvince().then(response => {
        provinceFormData.value = response.data;
    });
    getChildArea(provinceId).then(response => {
        cityFormData.value = response.data;
    });
    getChildArea(cityId).then(response => {
        areaFormData.value = response.data;
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const ids = row.scId || '';
    proxy.$modal.confirm('是否确认删除应急准备为"' + row.province + row.city + row.prefecture + '"的数据项？').then(function () {
        return delSeismicSetout(ids, '0');
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}


//处理附件格式
function eachFiles(fileName) {
    let deepFile = JSON.parse(JSON.stringify(proxy.$refs[fileName].fileList))
    let Ids = []
    for (var i = 0; i < deepFile.length; i++) {
        Ids.push(deepFile[i].attachId)
    }
    return Ids.join(",");
}

/** 提交按钮 */
function submitForm() {
    form.value.id = proxy.$refs['tabTableRef'].passFather().id || null;
    form.value.scId = proxy.$refs['tabTableRef'].passFather().id || null;
    // 处理附件
    form.value.scMedicalhelpAttachment = eachFiles('medicalFile');
    form.value.scBzxtjsqkAttachment = eachFiles('bzxtjsFile');
    form.value.scDzyjzztxhyatxAttachment = eachFiles('dzyjzztxFile');
    form.value.scDzyjgzjzAttachment = eachFiles('dzyjgzjzFile');
    form.value.scYjylkzqkAttachment = eachFiles('yjylkzFile');
    form.value.scSmxyjbzqkAttachment = eachFiles('smxyjbzFile');
    form.value.scCszhffqkAttachment = eachFiles('cszhffFile');
    form.value.scSfyyjyaAttachment = eachFiles('emergencyFile');
    form.value.scSfyyawjAttachment = eachFiles('documentFile');
    form.value.scYjdcxqAttachment = eachFiles('yjdcxqFile');
    form.value.scZdmbbznlAttachment = eachFiles('zdmbbzFile');
    form.value.scYyyqyjnlAttachment = eachFiles('yyyqyjnlFile');
    form.value.scKpxjhylAttachment = eachFiles('kpxjhylFile');
    form.value.scQtdftzyjzbcsAttachment = eachFiles('qtdftzFile');

    proxy.$refs["ruleFormRef"].validate(valid => {
        if (valid) {
            console.log(form)
            if (form.value.id != null) {
                updateSeismicSetout(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    showPopup.value = false;
                    getList();
                });
            } else {
                saveSeismicSetout(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    showPopup.value = false;
                    getList();
                });
            }
        }
    });
}

/** 搜索获取省市列表Start */
function getProvinceData() {
    getProvince().then(response => {
        provinceData.value = response.data;
    });
}

function chooseProvince(value) {
    queryParams.value.cityId = null;
    queryParams.value.areaId = null;
    cityData.value = [];
    areaData.value = [];
    getChildArea(value).then(response => {
        cityData.value = response.data;
    });
}

function chooseCity(value) {
    queryParams.value.areaId = null;
    areaData.value = [];
    getChildArea(value).then(response => {
        areaData.value = response.data;
    });
}
/** 搜索获取省市列表End */

/** 表单搜索获取省市列表Start */
function chooseFormProvince(value) {
    form.value.city = null;
    form.value.area = null;
    cityFormData.value = [];
    areaFormData.value = [];
    getChildArea(value).then(response => {
        cityFormData.value = response.data;
    });
    provinceData.value.forEach(item => {
        if (item.id == value) {
            form.value.province = item.name;
        }
    })
}


function chooseFormCity(value) {
    form.value.area = null;
    areaFormData.value = [];
    getChildArea(value).then(response => {
        areaFormData.value = response.data;
    });
    cityFormData.value.forEach(item => {
        if (item.id == value) {
            form.value.city = item.name;
        }
    })
}

function chooseFormArea(value) {
    areaFormData.value.forEach(item => {
        if (item.id == value) {
            form.value.prefecture = item.name;
        }
    })
}


function getProvinceFormData() {
    getProvince().then(response => {
        provinceFormData.value = response.data;
    });
}
// 权限
const isAdmin = async () => {
    let res = await getLanderRoles()
    const { code, data } = res
    if (code == 200) {
        const auth = data.split(',')
        return auth
    } else {
        return Promise.reject(new Error(data))
    }
}
const getDefaultProvice = async () => {
    try {
        let curAuth = await isAdmin()
        const type1 = curAuth.length == 1 && (curAuth.includes('省管理员') || curAuth.includes('省业务员'))
        const type2 = curAuth.length == 2 && curAuth.includes('省管理员') && curAuth.includes('省业务员')
        if (type1 || type2) {
            getLanderProvince().then(res => {
                if (res.code == 200) {
                    queryParams.value.provinceId = res.data
                    chooseProvince(queryParams.value.provinceId)
                    getList()
                }
            })
        } else {
            getList()
        }
    } catch (error) {

    }
}

/** 表单搜索获取省市列表End */

getDefaultProvice();
getProvinceData();

watch([() => form.value.provinceId, () => form.value.cityId, () => form.value.prefectureId], () => {
    const { provinceId, cityId, prefectureId } = form.value
    if (provinceId && cityId && prefectureId) {
        getAllSeismicSetout({ provinceId, cityId, prefectureId, page: 1, rows: 10 }).then(response => {
            getSeismicSetout(response.data.rows[0].scId).then(res => {
                form.value = { ...res.data, id:res.data.scId };
                console.log(form.value, res.data)
                scId.value = res.data.scId;
                title.value = "查看区县概况信息";
            });
        });
    }
})
</script>
  
<style lang="scss" scoped>
.mt15 {
    margin-top: 15px;
}
</style>